<?php
class AdminLoginFormClass
{
	public $AdminName;
	public $Password;
	public $Captcha;
	public $Message;
}
class GuoYiSystemLoginAction extends AppAction
{
	function __construct()
	{
		parent::__construct ();
	}
	//URL地址：http://apple.zhaosheng.com/index.php/login
	public function index()
	{
		ViewData::$title = "厦门国谊学校后台管理系统";
		ViewData::$form_data = new AdminLoginFormClass ();
		ViewData::$form_hint = new AdminLoginFormClass ();
		if ($_POST)
		{
			try
			{
				$this->loginForm ();
				$this->loginLogic ( ViewData::$form_data );
				Header( "Location:  ".siteUrl('AdminCenter')."");
				
			} catch ( Exception $e )
			{
				ViewData::$form_hint->Message = $e->getMessage ();
			}
		}
		BaseAction::loadView ( 'admin/adminLogin' );
	}
	
	private function loginForm()
	{
		ViewData::$form_data = BaseAction::parseForm ( "POST", ViewData::$form_data );
		ViewData::$form_hint->UserName = BaseAction::checkForm ( 'AdminName', 'POST', '姓名不能为空', array (2, 2, 64, "姓名长度错误" ), FALSE, FALSE );
		ViewData::$form_hint->Mobile = BaseAction::checkForm ( 'Password', 'POST', '密码不能为空', array (2, 6, 16, "密码长度错误" ), FALSE, FALSE );
		ViewData::$form_hint->Captcha = BaseAction::checkForm ( 'Captcha', 'POST', '验证码不能为空', array (2, 4, 4, "验证码长度错误" ), array ("isCharacter", "验证码格式有误" ), FALSE );
		if (! BaseAction::isObjectEmpty ( ViewData::$form_hint ))
		{
			return;
		}
		return;
	}
	/**
	 * 
	 * @param LoginFormClass $info
	 * @throws Exception
	 */
	private function loginLogic(AdminLoginFormClass $info)
	{
		if (! $this->checkCaptcha ( $info->Captcha ))
		{
			throw new Exception ( "验证码错误！" );
		}
		require_once APP_LIB_PATH . 'adminLib.php';
		$adminlib = new AdminLib ();
		$adminInfo = $adminlib->getByAdminName ( $info->AdminName );
		if (! $adminInfo)
		{
			throw new Exception ( "用户名不存在" );
		}
		if ($adminInfo['Password'] != md5 ( $info->Password ))
		{
			throw new Exception ( "用户名密码错误，请重新输入" );
		}
		$adminInfo['AdminGrant'] = json_decode( $adminInfo['AdminGrant'],TRUE );
		AdminSession::setAdminInfo ( $adminInfo );
		return TRUE;
	
	}
	
	/**
	 * 显示验证码
	 * @return void
	 */
	public function showCaptcha()
	{
		require_once SOURCE_EXT_PATH . 'library/CaptchaLib.php';
		AdminSession::setCaptcha ( CaptchaLib::getCode () );
		$code=AdminSession::getCaptcha();
		CaptchaLib::showImage ( $code );
	}
	
	/**
	 * 检查验证码
	 * @param string $inputCaptch
	 * @return string
	 */
	public function checkCaptcha($inputCaptch)
	{
		$code = AdminSession::getCaptcha ();
		AdminSession::clearCaptcha ();
		return strtolower ( $inputCaptch ) == strtolower ( $code );
	}
}
